const CabinetRespositories = require('../repositories/cabinetRepositories')

class CabinetServices {
  // 统一响应函数
  handleResponse(data, error, notFoundMessage = "实体未找到") {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return { code: 0, data: data };
  }

  async addNewCabinet(cabinetData) {
    const { number } = cabinetData;
    const hasCabinet = await CabinetRespositories.getCabinetByNum(number);
    if (hasCabinet)
      return {
        code: 1,
        msg: "柜子已存在",
        statusCode: 404,
      };
    const cabinet = await CabinetRespositories.addNewCabinet(cabinetData);
    return cabinet
      ? this.handleResponse(cabinet, null)
      : this.handleResponse(null, null, "添加失败");
  }

  async delCabinetByNum(number) {
    const bool = await CabinetRespositories.delCabinetByNum(number);
    return bool
      ? this.handleResponse("删除成功", null, null)
      : this.handleResponse(null, null, "删除失败");
  }

  async updateCabinetByNum(number, cabinetData) {
    const cabinet = await CabinetRespositories.getCabinetByNum(number);
    if (!cabinet) return this.handleResponse(null, null, "目标快递柜已存在");
    const bool = await CabinetRespositories.updateCabinetByNum(
      number,
      cabinetData
    );
    return bool
      ? this.handleResponse("更新成功", null, null)
      : this.handleResponse(null, null, "更新失败");
  }

  async getCabinetByNum(number) {
    const cabinet = await CabinetRespositories.getCabinetByNum(number);
    return this.handleResponse(cabinet, null, null);
  }

  async getCabinetsByGrpId(belongid) {
    const cabinets = await CabinetRespositories.getCabinetsByGrpId(belongid);
    return this.handleResponse(cabinets, null, null);
  }

  async getAllCabinets() {
    const cabinets = await CabinetRespositories.getAllCabinets();
    return this.handleResponse(cabinets);
  }

  async getCabinetByBelongAndNum(belong, number) {
    const cabinet = await CabinetRespositories.getCabinetByBelongAndNum(
      belong,
      number
    );
    return this.handleResponse(cabinet);
  }

  async closeCabinetByNum(belong, number) {
    const bool = await CabinetRespositories.closeCabinetByNum(belong, number);
    return bool
      ? this.handleResponse(belong + number + "号柜已关门", null, null)
      : this.handleResponse(null, null, "更新失败");
  }
}

module.exports = new CabinetServices()
